package classfile

// 字段表单
type MemberInfo struct {
	cp              ConstantPool // 常量池指针
	accessFlags     uint16
	nameIndex       uint16
	descriptorIndex uint16
	attributesCount uint16
	attributes      []AttributeInfo
}

// final 关键字定义的常量值
func (self *MemberInfo) ConstantValueAttribute() *ConstantValueAttribute {
	for _, attribute := range self.attributes {
		switch attribute.(type) {
		case *ConstantValueAttribute:
			return attribute.(*ConstantValueAttribute)
		}
	}
	return nil
}

func readCount(reader *ClassReader) uint16 {
	memberCount := reader.readUint16()
	return memberCount
}

func readMembers(reader *ClassReader, cp ConstantPool, memberCount uint16) []*MemberInfo {
	//memberCount := reader.readUint16()
	members := make([]*MemberInfo, memberCount)
	for i := range members {
		members[i] = readMember(reader, cp)
	}
	return members
}

func readMember(reader *ClassReader, cp ConstantPool) *MemberInfo {
	p1 := new(MemberInfo)
	p1.cp = cp
	p1.accessFlags = reader.readUint16()
	p1.nameIndex = reader.readUint16()
	p1.descriptorIndex = reader.readUint16()
	p1.attributesCount = readAttCount(reader)
	p1.attributes = readAttributes(reader, cp, p1.attributesCount)
	return p1
}

// getters
func (self *MemberInfo) AccessFlags() uint16 {
	return self.accessFlags
}

func (self *MemberInfo) Name() string {
	return self.cp.getUtf8(self.nameIndex)
}

func (self *MemberInfo) Descriptor() string {
	return self.cp.getUtf8(self.descriptorIndex)
}

func (self *MemberInfo) CodeAttribute() *CodeAttribute {
	for _, attributeInfo := range self.attributes {
		switch attributeInfo.(type) {
		case *CodeAttribute:
			return attributeInfo.(*CodeAttribute)
		}
	}
	return nil
}
